package com.kk.springboot_002.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kk.springboot_002.mapper.FruitMapper;
import com.kk.springboot_002.mapper.UserMapper;
import com.kk.springboot_002.pojo.Fruit;
import com.kk.springboot_002.pojo.User;
import com.kk.springboot_002.pojo.dto.FruitDto;
import com.kk.springboot_002.service.FruitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class FruitServiceImpl implements FruitService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FruitMapper fruitMapper;

    /**
     * 添加水果
     *
     * @param username
     * @param fruitDto
     */
    @Override
    public void addFruit(String username, FruitDto fruitDto) {
        User user = userMapper.findByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        Fruit existingFruit = fruitMapper.findFruitByNameAndUserId(fruitDto.getFruitName(), user.getId());
        if (existingFruit != null) {
            throw new RuntimeException("水果已存在");
        }
        // 成功添加水果
        fruitMapper.addFruit(fruitDto.getFruitName(), user.getId());
    }

    /**
     * 获取水果列表
     *
     * @param username
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Fruit> getFruits(String username, int page, int size) {
        User user = userMapper.findByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        try {
            log.info("开始查询水果列表，用户ID: {}", user.getId());
            // 在查询前调用 PageHelper.startPage()
            PageHelper.startPage(page, size);

            // 调用你的 MyBatis Mapper 方法，PageHelper 会拦截并处理分页
            List<Fruit> fruits = fruitMapper.findFruitByUserId(user.getId());

            // 使用 PageInfo 包装查询结果，它会自动封装分页信息
            PageInfo<Fruit> pageInfo = new PageInfo<>(fruits);
            log.info("分页信息：{}", pageInfo);
            return pageInfo;
        } catch (Exception e) {
            log.error("在 getFruits 方法中发生异常：", e);
            // 重新抛出异常，以便调用方能正确处理
            throw new RuntimeException("获取水果列表失败", e);
        }
    }
}
